package com.globussoft.filesystem;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor. this is comment.
 */

import com.globussoft.xml.SettingsXml;
import com.cloudminga.gui.*;
import com.globussoft.util.*;
import javax.swing.plaf.ColorUIResource;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;

/**
 * @version 1.1 01/15/99
 */
public class TestFileTree extends JPanel {

    DefaultTableModel dtm;
    static HashMap selectedNodes;
    boolean firstTime = true;
    private static long selectedFileSize;
    SettingsXml settingsXml;

    public SettingsXml getSettingsXml() {
        return settingsXml;
    }

//    private String getFormatedFileSize(long filesize) {
//        String size = "";
//        if (filesize >= 1024 * 1024 * 1024) {
//            size = String.valueOf(filesize / (1024 * 1024 * 1024)) + " " + "GB ";
//            filesize = filesize % (1024 * 1024 * 1024);
//        }
//        if (filesize >= 1024 * 1024) {
//            size = size + String.valueOf(filesize / (1024 * 1024)) + " " + "MB ";
//            filesize = filesize % (1024 * 1024);
//        }
//        if (filesize >= 1024) {
//            size = size + String.valueOf(filesize / (1024)) + " " + "KB ";
//            filesize = filesize % (1024);
//        }
//        if (filesize > 0) {
//            size = size + String.valueOf(filesize) + " " + "bytes";
//        }
//        return size;
//    }

//    private long getSelectedSizeFromFormatedString(String filesize) {//1 GB 2 MB 4 KB 820 bytes
//        long size = 0;
//        if (filesize.contains("GB")) {
//            size = (long) Integer.parseInt(filesize.substring(0, filesize.indexOf("GB")).trim()) * 1024 * 1024 * 1024;
//            filesize = filesize.substring(filesize.indexOf("GB") + "GB".length()).trim();
//        }
//        if (filesize.contains("MB")) {
//            size = size + (long) Integer.parseInt(filesize.substring(0, filesize.indexOf("MB")).trim()) * 1024 * 1024;
//            filesize = filesize.substring(filesize.indexOf("MB") + "MB".length()).trim();
//        }
//        if (filesize.contains("KB")) {
//            size = size + (long) Integer.parseInt(filesize.substring(0, filesize.indexOf("KB")).trim()) * 1024;
//            filesize = filesize.substring(filesize.indexOf("KB") + "KB".length()).trim();
//        }
//        if (filesize.contains("bytes")) {
//            size = size + (long) Integer.parseInt(filesize.substring(0, filesize.indexOf("bytes")).trim());
//            filesize = filesize.substring(filesize.indexOf("bytes") + "bytes".length()).trim();
//        }
//
//        return size;
//    }

    public static HashMap getSelectedNodes() {
        return selectedNodes;
    }

    public static void setSelectedNode(HashMap node) {
        selectedNodes = node;
    }

    public static String getSelectedFileSize() {
        return FormatedFileSize.getFormatedFileSize(selectedFileSize);
    }

   public static long getSelectedFilesSize() {
        return selectedFileSize;
   }


    public void setSelectedFileSize(long size) {
        selectedFileSize = size;
    }

    public static void addSelectedFileSize(long size) {
        selectedFileSize += size;
    }

    public static void removeSelectedFileSize(long size) {
        selectedFileSize -= size;
    }

    public static CheckNode DrawFolder(File file, CheckNode check) {
        /* Beginning of if block
        checking whether the file is directory or not */
        try {
            if (file.isDirectory()) {
                String[] children = file.list();

                int len = children.length;
                ////("length"+len);
                CheckNode[] ch = new CheckNode[len];
                for (int i = 0; i < len; i++) {
                    try {
                        if (new File(file, children[i]).isDirectory()
                                && children[i].toLowerCase().equals("windows") == false
                                && new File(file, children[i]).isHidden() == false) {
                            ch[i] = new CheckNode(children[i]);
                            ch[i].setSelected(false);
                            check.add(ch[i]);
                            //  DrawFolder(new File(file, children[i]), ch[i]);
                        }
                    } catch (Exception ex) {
                    }

                }
            }/*end of if block*/ else {
            }
        } catch (Exception ex) {
        }
        return check;
    }
    /*code for Directory Tree Structure*/

    public static void drawFolder(CheckNode root, String filename, HashMap checkNodeObjectMap, String rootName) {
        filename = filename.toLowerCase();
        if (filename.contains("/")) {
            String node = filename.substring(0, filename.indexOf("/"));
            if (rootName.equals("") == false) {
                rootName = rootName + "/" + node;
            } else {
                rootName += node;
            }
            CheckNode nodeObj = (CheckNode) checkNodeObjectMap.get(rootName);
            if (nodeObj == null) {
                nodeObj = new CheckNode(node);
                root.add(nodeObj);
                checkNodeObjectMap.put(rootName, nodeObj);
            }
            filename = filename.substring(filename.indexOf("/") + 1);

            drawFolder(nodeObj, filename, checkNodeObjectMap, rootName);
        }

    }

    public static JTree getTree(Object[][] obj) {
        HashMap checkNodeObjectMap = new HashMap();
        int len = obj.length;
        CheckNode root = new CheckNode("root");
        // Object[] files = map.keySet().toArray();
        for (int i = 0; i < len; i++) {
            drawFolder(root, obj[i][0].toString(), checkNodeObjectMap, "");
        }
        return new JTree(root);
    }

    public static JTree getTree() {
        File[] file = File.listRoots();
        int len = file.length;
        CheckNode[] ch = new CheckNode[len];
        CheckNode root = new CheckNode("root");
        for (int i = 0; i < len; i++) {
            try {
                ch[i] = DrawFolder(file[i], new CheckNode(file[i].toString()));
                ch[i].setSelected(false);
                root.add(ch[i]);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return new JTree(root);
    }
    public static final ImageIcon ICON_COMPUTER =
            new ImageIcon("computer.gif");
    public static final ImageIcon ICON_DISK =
            new ImageIcon("disk.gif");
    public static final ImageIcon ICON_FOLDER =
            new ImageIcon("folder.gif");
    public static final ImageIcon ICON_EXPANDEDFOLDER =
            new ImageIcon("expandedfolder.gif");
    protected JTree m_tree;
    protected DefaultTreeModel m_model;
    protected JTextField m_display;

    public TestFileTree() {
        new Thread() {

            @Override
            public void run() {
                settingsXml = new SettingsXml();
                settingsXml.ReadGeneralXml("Settings.xml");
            }
        }.start();
        selectedFileSize = 0;
        selectedNodes = new HashMap();
        setLayout(new GridLayout());
        JTree m_tree = getTree();
        //JTree m_tree = getTree();
        m_tree.setCellRenderer(new CheckRenderer());
        /*Sets the TreeCellRenderer
        that will be used to draw each cell.*/
        m_tree.putClientProperty("JTree.lineStyle", "Angled");
        m_tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
        m_tree.addMouseListener(new NodeSelectionListener(m_tree));
        final JScrollPane s = new JScrollPane(m_tree);
        s.setSize(800, 1000);
        this.add(s, BorderLayout.CENTER);
        this.setSize(1000, 1000);

    }

    public TestFileTree(Object[][] obj) {
        new Thread() {

            @Override
            public void run() {
                settingsXml = new SettingsXml();
                settingsXml.ReadGeneralXml("Settings.xml");
            }
        }.start();
        selectedFileSize = 0;
        selectedNodes = new HashMap();
        setLayout(new GridLayout());
        JTree m_tree = getTree(obj);
        //JTree m_tree = getTree();
        m_tree.setCellRenderer(new CheckRenderer());
        /*Sets the TreeCellRenderer
        that will be used to draw each cell.*/
        m_tree.putClientProperty("JTree.lineStyle", "Angled");
        m_tree.getSelectionModel().setSelectionMode(
                TreeSelectionModel.SINGLE_TREE_SELECTION);
        m_tree.addMouseListener(new NodeSelectionListener(m_tree));
        final JScrollPane s = new JScrollPane(m_tree);
        s.setSize(800, 1000);
        this.add(s, BorderLayout.CENTER);
        this.setSize(1000, 1000);

    }

    DefaultMutableTreeNode getTreeNode(TreePath path) {
        return (DefaultMutableTreeNode) (path.getLastPathComponent());
    }

    FileNode getFileNode(DefaultMutableTreeNode node) {
        if (node == null) {
            return null;
        }
        Object obj = node.getUserObject();
        if (obj instanceof IconData) {
            obj = ((IconData) obj).getObject();
        }
        if (obj instanceof FileNode) {
            return (FileNode) obj;
        } else {
            return null;
        }
    }

    // Make sure expansion is threaded and updating the tree model
    // only occurs within the event dispatching thread.
    class DirExpansionListener implements TreeExpansionListener {

        @Override
        public void treeExpanded(TreeExpansionEvent event) {
            final DefaultMutableTreeNode node = getTreeNode(
                    event.getPath());
            final FileNode fnode = getFileNode(node);

            Thread runner = new Thread() {

                @Override
                public void run() {
                    if (fnode != null && fnode.expand(node)) {
                        Runnable runnable = new Runnable() {

                            @Override
                            public void run() {
                                m_model.reload(node);
                            }
                        };
                        SwingUtilities.invokeLater(runnable);
                    }
                }
            };
            runner.start();
        }

        @Override
        public void treeCollapsed(TreeExpansionEvent event) {
        }
    }

    /*class defines the requirements for an object that displays a tree node*/
    class CheckRenderer extends JPanel implements TreeCellRenderer, ItemListener {

        protected JCheckBox checkboxlefttable;
        protected TreeLabel nodelabel;
//    CheckBoxRightTable chk;
//

        public CheckRenderer() {
            setLayout(null);
            checkboxlefttable = new JCheckBox();
            add(checkboxlefttable);
            //sendChecboxreference(checkboxlefttable);
            checkboxlefttable.addItemListener(this);
            add(nodelabel = new TreeLabel());
            checkboxlefttable.setBackground(Color.white);
            nodelabel.setForeground(UIManager.getColor("Tree.textForeground"));
        }

        /*code to Set the value of the current tree cell to value.*/
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean isSelected, boolean expanded, boolean leaf, int row,
                boolean hasFocus) {
            String stringValue = tree.convertValueToText(value, isSelected,
                    expanded, leaf, row, hasFocus);
            setEnabled(tree.isEnabled());
            checkboxlefttable.setSelected(((CheckNode) value).isSelected());
            nodelabel.setFont(tree.getFont());/*sets font*/
            nodelabel.setText(stringValue);/*sets Text*/
            nodelabel.setSelected(isSelected);
            nodelabel.setFocus(hasFocus);

            if (leaf) {

                nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
            } else if (expanded) {
                nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
            } else {
                nodelabel.setIcon(UIManager.getIcon("Tree.openIcon"));
            }
            return this;
        }

        @Override
        /*sets the size of CheckBox*/
        public Dimension getPreferredSize() {
            Dimension checkboxsize = checkboxlefttable.getPreferredSize();
            Dimension nodelabelsize = nodelabel.getPreferredSize();
            return new Dimension(checkboxsize.width + nodelabelsize.width,
                    (checkboxsize.height < nodelabelsize.height ? nodelabelsize.height
                    : checkboxsize.height));
        }

        @Override
        //sets the layout of checkbox
        public void doLayout() {
            Dimension checkboxsize = checkboxlefttable.getPreferredSize();
            Dimension nodelabelsize = nodelabel.getPreferredSize();
            int checkboxheight = -1;
            int nodelabelheight = -1;
            if (checkboxsize.height < nodelabelsize.height) {
                checkboxheight = (nodelabelsize.height - checkboxsize.height) / 2;
            } else {
                nodelabelheight = (checkboxsize.height - nodelabelsize.height) / 2;
            }
            checkboxlefttable.setLocation(0, checkboxheight);
            checkboxlefttable.setBounds(0, checkboxheight, checkboxsize.width, checkboxsize.height);
            nodelabel.setLocation(checkboxsize.width, nodelabelheight);
            nodelabel.setBounds(checkboxsize.width, nodelabelheight, nodelabelsize.width, nodelabelsize.height);
        }

        @Override
        //set the backgroundcolor of the Checkbox
        public void setBackground(Color color) {
            if (color instanceof ColorUIResource) {
                color = null;
            }
            super.setBackground(color);
        }

        /*code for Checkbox State Change */
        @Override
        public void itemStateChanged(ItemEvent itemEvent) {



            int k = 1;

            if (checkboxlefttable.isSelected()) {
                for (k = 0; k < MainForm.fileTable.getRowCount(); k++) {
                    MainForm.fileTable.setValueAt(Boolean.TRUE, k, 0);
//                MainForm.fileTable.tableChanged(new TableModelEvent(MainForm.fileTable.getModel()));
//                this.revalidate();
//                this.repaint();

                }
            } else {
                // MainForm.fileTable.setValueAt(Boolean.FALSE, k, 0);
            }
        }

        /* Code for fileTree NodeLabel */
        public class TreeLabel extends JLabel {

            boolean isSelected;
            boolean hasFocus;

            public TreeLabel() {
            }

            @Override
            public void paint(Graphics g) {
                String str;
                if ((str = getText()) != null) {
                    if (0 < str.length()) {
                        if (isSelected) {
                            g.setColor(UIManager.getColor("Tree.selectionBackground"));
                        } else {
                            g.setColor(UIManager.getColor("Tree.textBackground"));
                        }
                        Dimension d = getPreferredSize();
                        int imageOffset = 0;
                        Icon currentI = getIcon();
                        if (currentI != null) {
                            imageOffset = currentI.getIconWidth() + Math.max(0, getIconTextGap() - 4);
                        }
                        g.fillRect(imageOffset, 0, d.width - 2 - imageOffset,
                                d.height);
                        if (hasFocus) {
                            g.setColor(UIManager.getColor("Tree.selectionBorderColor"));
                            g.drawRect(imageOffset, 0, d.width - 2 - imageOffset,
                                    d.height - 1);
                        }
                    }
                }
                super.paint(g);
            }

            @Override
            public Dimension getPreferredSize() {
                Dimension nodelabelDimension = super.getPreferredSize();
                if (nodelabelDimension != null) {
                    nodelabelDimension = new Dimension(nodelabelDimension.width + 5,
                            nodelabelDimension.height);
                }
                return nodelabelDimension;
            }

            public void setSelected(boolean isSelected) {
                this.isSelected = isSelected;
            }

            public void setFocus(boolean hasFocus) {
                this.hasFocus = hasFocus;
            }
        }
    }

    public static void main(String argv[]) {
        HashMap map = new HashMap();
        map.put("C:\\Sunil\\kumar\\choudhary", true);
        map.put("C:\\Sunil\\BIT\\DURG", true);
        // new TestFileTree(map);
    }
    /*code to display filelist of subsequest directories on mouseclickevent
    of the node of the tree*/

    class NodeSelectionListener extends MouseAdapter {

        JTree tree;      /*instance of JTree*/


        NodeSelectionListener(JTree tree) {

            this.tree = tree;
            //("mouse clicked");

        }

        @Override
        public void mouseClicked(MouseEvent e) {
            if (MainForm.getSelectionButton().equals("filesystemButton")) {
                dtm = (DefaultTableModel) MainForm.fileTable.getModel();
                int si = dtm.getDataVector().size();
              //  System.out.println(si);
                for (int i2 = si - 1; i2 >= 0; i2--) {
                    try {
                        String size = dtm.getValueAt(i2, 3).toString().trim();
                        dtm.removeRow(i2);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                int x = e.getX();
                int y = e.getY();
                int row = tree.getRowForLocation(x, y);
              //  System.out.println(tree.getClosestPathForLocation(x, y));
                /* for getting absolutefilepath */
                TreePath path = tree.getPathForRow(row);
                //("path $$" + path+" row ="+row);
                if (path == null) {
                    path = tree.getClosestPathForLocation(x, y);
                }
                if (path != null) {
                    try {
                        CheckNode chh = (CheckNode) path.getLastPathComponent();
                       // System.out.println(path + " is checked" + chh.isSelected);
                        String path_str = path.toString();
                        path_str = path_str.replace("[", "");
                        path_str = path_str.replace("]", "");
                        String path_var[] = path_str.split(",");
                        String absult_path = "";
                        String absult_path1 = "";
                        for (int i = 1; i < path_var.length; i++) {
                            if (i == 1) {
                                absult_path = path_var[i].replace("\\", "/");
                                absult_path1 = absult_path;
                            } else {
                                absult_path = absult_path + "\\" + path_var[i].trim();
                                absult_path1 = absult_path1 + "\\" + path_var[i].trim();
                            }
                        }
                        //("Absult Path "+absult_path1);
                        dtm = (DefaultTableModel) MainForm.fileTable.getModel();
                        //this statement removes all rows from JTABLE
                        dtm.getDataVector().removeAllElements();
                        FileList filelist = new FileList();
                        /*filelist are store in a hashmap*/
                        HashMap hm = new HashMap();
                        hm = filelist.setRootDir(absult_path1);
                        int j = hm.size();
                        int i = 0;
                        Date date;
                        String strDate;
                        SimpleDateFormat sdf;
                        JFileChooser filechooser = new JFileChooser(); //To get the FileType
                        String filetype;
                        String size = null;
                        long filesize;
                        CheckNode node = (CheckNode) path.getLastPathComponent();
                        while (!hm.isEmpty()) {
                            String filepath = (String) hm.get(i);
                            File file = new File(filepath);
                            filetype = filechooser.getTypeDescription(file);
                            date = new Date();
                            sdf = new SimpleDateFormat("dd/MM/yy hh:mm:ss");
                            strDate = sdf.format(date);
                            filesize = file.length();
                            /*code to check the file size in Bytes,KB,MB,GB*/
                            size = FormatedFileSize.getFormatedFileSize(filesize);
                            dtm.addRow(new Object[]{!chh.isSelected, file.getName(), hm.get(i).toString().substring(0, hm.get(i).toString().replace("\\", "/").lastIndexOf("/")), size, filetype, strDate});
                            //adding the filedata in  a fileTable row
                            if (chh.isSelected == false) {
                                addSelectedFileSize(filesize);
                                selectedNodes.put(hm.get(i).toString().toLowerCase().replace("\\", "/"), filesize);
                            }
                            hm.remove(i);
                            i++;
                        }

                        boolean isSelected = !(node.isSelected());
                        node.setSelected(isSelected);
                        ((DefaultTreeModel) tree.getModel()).nodeChanged(node);//odeChanged(node);
                        Enumeration E = node.children();
                        boolean checkThisNodeIsRoot = checkRoot(new File(node.toString()));
                        String temp_path = path.toString().substring(path.toString().indexOf(",") + 1, path.toString().indexOf("]")).trim().replace("\\, ", "/").replace(", ", "/");
                        if (!chh.isSelected) {
                            selectedNodes = removeNodeAndFiles(temp_path.replace("\\", "/").toLowerCase(), selectedNodes);
                        }
                        if (E.hasMoreElements()) {
                            while (E.hasMoreElements()) {
                                CheckNode ch = (CheckNode) E.nextElement();
                                File f = new File(temp_path + "/" + ch);
                                File[] files = f.listFiles();
                                if (files != null) {
                                    int len = files.length;
                                    if (len != ch.getChildCount()) {
                                        for (int k = 0; k < len; k++) {
                                            if (files[k].isHidden() == false && files[k].isDirectory()) {
                                                CheckNode check = new CheckNode(files[k].getName());
                                                check.setSelected(false);
                                                ((DefaultTreeModel) tree.getModel()).insertNodeInto(check, ch, 0);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                //  SelectedNodes((CheckNode) tree.getModel().getRoot(), selectedNodes, "");
                Object[] ob = selectedNodes.entrySet().toArray();
              //  System.out.println("Selected Items" + selectedNodes.size());
                for (int ii = 0; ii < ob.length; ii++) {
                    // System.out.println(ob[ii]);
                }

                MainForm.fileTable.updateUI();
            } else// if Restore is Selected
            {
                dtm = (DefaultTableModel) MainForm.RestoreRightTable.getModel();
                int si = dtm.getDataVector().size();
              //  System.out.println(si);
                for (int i2 = si - 1; i2 >= 0; i2--) {
                    try {
                        dtm.removeRow(i2);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                int x = e.getX();
                int y = e.getY();
                int row = tree.getRowForLocation(x, y);
              //  System.out.println(tree.getClosestPathForLocation(x, y));
                /* for getting absolutefilepath */
                TreePath path = tree.getPathForRow(row);

                //("path $$" + path+" row ="+row);

                if (path == null) {
                    path = tree.getClosestPathForLocation(x, y);
                }
                if (path != null) {
                    try {
                        CheckNode chh = (CheckNode) path.getLastPathComponent();
                      //  System.out.println(path + " is checked" + chh.isSelected);
                        String path_str = path.toString();
                        path_str = path_str.replace("[", "");
                        path_str = path_str.replace("]", "");
                        String path_var[] = path_str.split(",");
                        String absult_path = "";
                        String absult_path1 = "";
                        for (int i = 1; i < path_var.length; i++) {
                            if (i == 1) {
                                absult_path = path_var[i].replace("\\", "/");
                                absult_path1 = absult_path;
                            } else {
                                absult_path = absult_path + "\\" + path_var[i].trim();
                                absult_path1 = absult_path1 + "\\" + path_var[i].trim();
                            }
                        }
                        //("Absult Path "+absult_path1);
                        dtm = (DefaultTableModel) MainForm.RestoreRightTable.getModel();
                        //this statement removes all rows from JTABLE
                        dtm.getDataVector().removeAllElements();
                        Object[][] RestoreContent = MainForm.getRestoreInfo();
                        // Object[] objArr = RestoreContent.keySet().toArray();
                        CheckNode node = (CheckNode) path.getLastPathComponent();
                        int len = RestoreContent.length;
                        for (int j = 0; j < len; j++) {
                            String filepath = RestoreContent[j][0].toString();
                            String fileName = filepath.trim().toLowerCase().replace("\\", "/").substring(filepath.trim().toLowerCase().replace("\\", "/").lastIndexOf("/") + 1);
                            String dirName = filepath.trim().toLowerCase().replace("\\", "/").substring(0, filepath.trim().toLowerCase().replace("\\", "/").lastIndexOf("/"));
                            if (dirName.equals(absult_path1.trim().toLowerCase().replace("\\", "/"))) {
                                //Object[] tempObject = (Object[]) RestoreContent.get(filepath);
                                dtm.addRow(new Object[]{!(node.isSelected), fileName, dirName, RestoreContent[j][1], RestoreContent[j][2], RestoreContent[j][3]});
                                if (!(node.isSelected)) {
                                    selectedNodes.put(filepath.trim().toLowerCase().replace("\\", "/"),new File(filepath).length());
                                } else {
                                    selectedNodes.remove(filepath.trim().toLowerCase().replace("\\", "/"));
                                }
                            }
                        }
                        boolean isSelected = !(node.isSelected());
                        ((DefaultTreeModel) tree.getModel()).nodeChanged(node);
                        node.setSelected(isSelected);
                        if (!isSelected) {
                        }
                        if (node.getSelectionMode() == CheckNode.DIG_IN_SELECTION) {
                            if (node.isSelected) {
                            } else {
                                tree.collapsePath(path);
                            }
                        }
//                        System.out.println("Row=" + row);
//                        //System.out.println(path);
//                        Enumeration E = node.children();
//                        String temp_path = path.toString().substring(path.toString().indexOf(",") + 1, path.toString().indexOf("]")).trim().replace("\\, ", "/").replace(", ", "/");
//                        if (E.hasMoreElements()) {
//                            while (E.hasMoreElements()) {
//                                CheckNode ch = (CheckNode) E.nextElement();
//                                if (ch.isSelected()) {
//                                    selectedNodes = removeNodeAndFiles(temp_path.replace("\\", "/").toLowerCase(), selectedNodes);
//                                }
//                            }
//                        }
//                        else {
//                            if (node.isSelected == false) {
//                                selectedNodes = removeNodeAndFiles(temp_path.replace("/", "\\").toLowerCase(), selectedNodes);
//                            }
//                        }

                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                //  SelectedNodes((CheckNode) tree.getModel().getRoot(), selectedNodes, "");
                Object[] ob = selectedNodes.entrySet().toArray();
              //  System.out.println("Selected Items" + selectedNodes.size());
                for (int ii = 0; ii < ob.length; ii++) {
                    System.out.println(ob[ii]);
                }
            }
            System.out.println(getSelectedFileSize());
            long quota =(long) settingsXml.getQuota() * 1024 * 1024 * 1024;
            MainForm.UsedDisplayLabel.setText(""+FormatedFileSize.getFormatedFileSize(selectedFileSize));
            MainForm.QuotaDisplayLabel.setText(""+settingsXml.getQuota()+" GB");
            MainForm.FileDisplayLabel.setText(""+selectedNodes.size());
            int  percentUsed=(int)(selectedFileSize*100/quota);            
            MainForm.RemainingDisplayLabel.setText(""+FormatedFileSize.getFormatedFileSize(quota-selectedFileSize));
            MainForm.ProgressBar.setValue(percentUsed);

//           System.out.println("Quota"+quota);
//           System.out.println("SelectedFilesSize"+selectedFileSize);
//           System.out.println("Selected Files"+selectedNodes.size());

        }

        void SelectedNodes(CheckNode checkNode, HashMap hash, String path) {
            Enumeration en = checkNode.children();
            while (en.hasMoreElements()) {
                CheckNode ch = (CheckNode) en.nextElement();
                // System.out.println(checkNode+"&&&"+path);
                if (ch.isSelected) {
                    if (path.endsWith("\\")) {
                        SelectedNodes(ch, hash, path + ch + "\\");
                    } else {
                        SelectedNodes(ch, hash, path + ch);
                    }
                    hash.put((path + ch).replace("\\", "/").toLowerCase(), false);

                }
            }
        }

        private HashMap removeNodeAndFiles(String temp_path, HashMap selectedNodes) {
            Object[] obj = selectedNodes.keySet().toArray();
            int len = obj.length;
            for (int i = 0; i < len; i++) {
                if (obj[i].toString().startsWith(temp_path)) {
                    System.out.println("Removing " + obj[i].toString() + "   " + selectedNodes.containsKey(obj[i].toString()) + selectedNodes.size());
                    long size = Long.parseLong(selectedNodes.get(obj[i].toString().toLowerCase().replace("\\", "/")).toString());
                    selectedNodes.remove(obj[i].toString().toLowerCase().replace("\\", "/"));
                    removeSelectedFileSize(size);
                    System.out.println(selectedNodes.size());
                }
            }
            return selectedNodes;
        }

        private boolean checkRoot(File file) {
            boolean flag = false;
            File[] files = File.listRoots();
            for (int i = 0; i < files.length; i++) {
                if (file.getName().equals(files[i].getName())) {
                    flag = true;
                }
            }
            return flag;
        }
    }

    class IconCellRenderer
            extends JLabel
            implements TreeCellRenderer {

        protected Color m_textSelectionColor;
        protected Color m_textNonSelectionColor;
        protected Color m_bkSelectionColor;
        protected Color m_bkNonSelectionColor;
        protected Color m_borderSelectionColor;
        protected boolean m_selected;

        public IconCellRenderer() {
            super();
            m_textSelectionColor = UIManager.getColor(
                    "Tree.selectionForeground");
            m_textNonSelectionColor = UIManager.getColor(
                    "Tree.textForeground");
            m_bkSelectionColor = UIManager.getColor(
                    "Tree.selectionBackground");
            m_bkNonSelectionColor = UIManager.getColor(
                    "Tree.textBackground");
            m_borderSelectionColor = UIManager.getColor(
                    "Tree.selectionBorderColor");
            setOpaque(false);
        }

        @Override
        public Component getTreeCellRendererComponent(JTree tree,
                Object value, boolean sel, boolean expanded, boolean leaf,
                int row, boolean hasFocus) {
            DefaultMutableTreeNode node =
                    (DefaultMutableTreeNode) value;
            Object obj = node.getUserObject();
            setText(obj.toString());

            if (obj instanceof Boolean) {
                setText("Retrieving data...");
            }

            if (obj instanceof IconData) {
                IconData idata = (IconData) obj;
                if (expanded) {
                    setIcon(idata.getExpandedIcon());
                } else {
                    setIcon(idata.getIcon());
                }
            } else {
                setIcon(null);
            }

            setFont(tree.getFont());
            setForeground(sel ? m_textSelectionColor
                    : m_textNonSelectionColor);
            setBackground(sel ? m_bkSelectionColor
                    : m_bkNonSelectionColor);
            m_selected = sel;
            return this;
        }

        @Override
        public void paintComponent(Graphics g) {
            Color bColor = getBackground();
            Icon icon = getIcon();

            g.setColor(bColor);
            int offset = 0;
            if (icon != null && getText() != null) {
                offset = (icon.getIconWidth() + getIconTextGap());
            }
            g.fillRect(offset, 0, getWidth() - 1 - offset,
                    getHeight() - 1);

            if (m_selected) {
                g.setColor(m_borderSelectionColor);
                g.drawRect(offset, 0, getWidth() - 1 - offset, getHeight() - 1);
            }
            super.paintComponent(g);
        }
    }

    class IconData {

        protected Icon m_icon;
        protected Icon m_expandedIcon;
        protected Object m_data;

        public IconData(Icon icon, Object data) {
            m_icon = icon;
            m_expandedIcon = null;
            m_data = data;
        }

        public IconData(Icon icon, Icon expandedIcon, Object data) {
            m_icon = icon;
            m_expandedIcon = expandedIcon;
            m_data = data;
        }

        public Icon getIcon() {
            return m_icon;
        }

        public Icon getExpandedIcon() {
            return m_expandedIcon != null ? m_expandedIcon : m_icon;
        }

        public Object getObject() {
            return m_data;
        }

        @Override
        public String toString() {
            return m_data.toString();
        }
    }

    class FileNode {

        protected File m_file;

        public FileNode(File file) {
            m_file = file;
        }

        public File getFile() {
            return m_file;
        }

        @Override
        public String toString() {
            return m_file.getName().length() > 0 ? m_file.getName()
                    : m_file.getPath();
        }

        public boolean expand(DefaultMutableTreeNode parent) {
            DefaultMutableTreeNode flag =
                    (DefaultMutableTreeNode) parent.getFirstChild();
            if (flag == null) // No flag
            {
                return false;
            }
            Object obj = flag.getUserObject();
            if (!(obj instanceof Boolean)) {
                return false;      // Already expanded
            }
            parent.removeAllChildren();  // Remove Flag

            File[] files = listFiles();
            if (files == null) {
                return true;
            }

            Vector v = new Vector();

            for (int k = 0; k < files.length; k++) {
                File f = files[k];
                if (!(f.isDirectory())) {
                    continue;
                }

                FileNode newNode = new FileNode(f);

                boolean isAdded = false;
                for (int i = 0; i < v.size(); i++) {
                    FileNode nd = (FileNode) v.elementAt(i);
                    if (newNode.compareTo(nd) < 0) {
                        v.insertElementAt(newNode, i);
                        isAdded = true;
                        break;
                    }
                }
                if (!isAdded) {
                    v.addElement(newNode);
                }
            }

            for (int i = 0; i < v.size(); i++) {
                FileNode nd = (FileNode) v.elementAt(i);
                IconData idata = new IconData(TestFileTree.ICON_FOLDER,
                        TestFileTree.ICON_EXPANDEDFOLDER, nd);
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
                parent.add(node);

                if (nd.hasSubDirs()) {
                    node.add(new DefaultMutableTreeNode(
                            new Boolean(true)));
                }
            }

            return true;
        }

        public boolean hasSubDirs() {
            File[] files = listFiles();
            if (files == null) {
                return false;
            }
            for (int k = 0; k < files.length; k++) {
                if (files[k].isDirectory()) {
                    return true;
                }
            }
            return false;
        }

        public int compareTo(FileNode toCompare) {
            return m_file.getName().compareToIgnoreCase(
                    toCompare.m_file.getName());
        }

        protected File[] listFiles() {
            if (!m_file.isDirectory()) {
                return null;
            }
            try {
                return m_file.listFiles();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null,
                        "Error reading directory " + m_file.getAbsolutePath(),
                        "Warning", JOptionPane.WARNING_MESSAGE);
                return null;
            }
        }
    }
}
